package com.xthh._function;

import android.content.Context;

import com.xthh._function._language.HH_LanguageUtil;
import com.xthh._function.js.MyJSON;
import com.xthh._struct.HH_T_Material;
import com.xthh._struct.HH_T_ThemeList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HH_ProtocolHttp {
    public static String TAG = "ProtocolHttp";

    public static String GetServerUrl(int type){
        switch (type){
            case 0:{
                return "http://api.seekink.cn:8092/prod-api"; // 国内
            }
            case 1:{
                return "http://iot.seekink.com/cloud/prod-api"; // 国外
            }
            case 2:{
                return "http://iot.seekink.cn:8090/cloud/prod-api"; //  测试服务器
            }
            default:{
                return "http://10.41.1.84:8088"; // 本地
            }
        }
    }


    public static String GetWifiUserJsonInfo(String name, String pwd) {
        JSONObject object = new JSONObject();

        try {
            object.put("username", name);
            object.put("password", pwd);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return (String.valueOf(object));
    }

    public static String WifiLoginServer(String msg, int type) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, msg);
        Request request = new Request.Builder().url(GetServerUrl(type) + "/api/v1/user/login" ).post(body).build();
        Response response = client.newCall(request).execute();

        if (response.code() == 200 && !(response.body() == null)) {
            return GetJsonWifiKeyData(Objects.requireNonNull(response.body()).string());
        }
        return "";
    }

    public static String GetJsonWifiKeyData(String jsonData) {
        try {
            JSONObject object = new JSONObject(jsonData);
            int code = object.getInt("code");
            if (code == 200){
                String data = object.getString("data");
                return data;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String GetJsonWifiInfoMacs(String jsonData) {
        try {
            JSONObject object = new JSONObject(jsonData);
            int code = object.getInt("code");
            if (code == 200){
                String data = object.getString("data");
                return data;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return "";
    }

    // 获取所有设备状态
    public static JSONObject WifiGetMacsStatus(String msg, int wifiServderUrlType, String wifiUserKey) throws IOException {
        OkHttpClient client = new OkHttpClient();

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        RequestBody body = RequestBody.create(JSON, msg);

        Request request = new Request.Builder()
                //这里必须手动设置为json内容类型
                .addHeader("content-type", "application/json")
                //设置token
                .addHeader("Authorization","Bearer " + wifiUserKey)
                //参数放到链接后面
                .url(GetServerUrl(wifiServderUrlType) + "/api/v1/label/listByMacs")
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        if (response.code() == 200 && !(response.body() == null)) {
            //return GetJsonWifiInfoMacs(Objects.requireNonNull(response.body()).string());
            try {
                return new JSONObject(Objects.requireNonNull(response.body()).string());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    // 获取所有设备状态
    public static JSONObject WifiBrushPic(String picPath, String mac, int wifiServderUrlType, String wifiUserKey) throws IOException {
        OkHttpClient client = new OkHttpClient();
        File file = new File(picPath);
        // 构建请求体
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .addFormDataPart("labelMac", mac)
                .build();

        Request request = new Request.Builder()
                //这里必须手动设置为json内容类型
                .addHeader("content-type", "application/json")
                //设置token
                .addHeader("Authorization","Bearer " + wifiUserKey)
                //参数放到链接后面
                .url(GetServerUrl(wifiServderUrlType) + "/api/v1/label/brushPic")
                .post(requestBody)
                .build();

        // 执行请求
        try {
            Response response = client.newCall(request).execute();

            if (response.code() == 200 && !(response.body() == null)) {
                //return GetJsonWifiInfoMacs(Objects.requireNonNull(response.body()).string());
                try {
                    return new JSONObject(Objects.requireNonNull(response.body()).string());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (response.isSuccessful()) {
                // 请求成功处理
                System.out.println("File uploaded successfully!");
                System.out.println("Response: " + response.body().string());
            } else {
                // 请求失败处理
                System.out.println("File upload failed!");
                System.out.println("Response: " + response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }



    public static HashMap<String, HH_T_ThemeList> GetThemeList(Context ctx, String verificationCode, int urlType) throws IOException {

        HashMap<String, HH_T_ThemeList> bitmapHashMap = new HashMap<String, HH_T_ThemeList>();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("Authorization", verificationCode)
                .addHeader("Accept-Language", HH_LanguageUtil.IsChineseLanguage(ctx) ? "zh-Hans" : "en")
                .url(GetServerUrl(urlType) + "/api/v1/theme/list").build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response != null && response.isSuccessful()) {
            String info;
            try {
                info = response.body().string();
                return GetThemeInfo(info);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

        }

        return null;
    }

    public static HashMap<String, HH_T_ThemeList> GetThemeInfo(String jsonData) {
        //List<T_ThemeList> list = new ArrayList<>();
        HashMap<String, HH_T_ThemeList> list = new HashMap<String, HH_T_ThemeList>();

        try {
            JSONObject object = new JSONObject(jsonData);
            int code = MyJSON.getInt(object, "code");
            if (code == 200){
                JSONArray rows = MyJSON.getJSONArray(object, "rows");
                for (int n = 0; n < rows.length(); n++){
                    JSONObject js = rows.getJSONObject(n);
                    String id = MyJSON.getString(js,"id");
                    String name = MyJSON.getString(js,"name");
                    String nameCn = MyJSON.getString(js,"nameCn");
                    String nameEn = MyJSON.getString(js,"nameEn");
                    String nameTw = MyJSON.getString(js,"nameTw");
                    String nameRu = MyJSON.getString(js,"nameRu");
                    String namePt = MyJSON.getString(js,"namePt");
                    String nameDe = MyJSON.getString(js,"nameDe");
                    String nameJa = MyJSON.getString(js,"nameJa");

                    HH_T_ThemeList tl = new HH_T_ThemeList(id, name, nameCn, nameEn, nameTw, nameRu, namePt, nameDe, nameJa);
                    //list.add(tl);
                    list.put(id, tl);
                }
            }
        } catch (JSONException e) {
            //Logging.i(TAG, new Exception(), e.toString());
        }

        return list;
    }



    public static List<HH_T_Material> GetMaterialList(Context ctx, String verificationCode, int urlType,
            String deviceModelSavePath) throws IOException {

        String url = String.format("%s/api/v1/material/list",
                GetServerUrl(urlType));


        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                //.addHeader("ratio", String.format("%d*%d", DATA.globa_current_use_tag_info.getWidth(), DATA.globa_current_use_tag_info.getHeight()))
                .addHeader("Authorization", verificationCode)
                //.addHeader("color", color)
                .addHeader("Accept-Language", HH_LanguageUtil.IsChineseLanguage(ctx) ? "zh-Hans" : "en")
                .url(url).build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (response != null && response.isSuccessful()) {
            String info;
            try {
                info = response.body().string();
                return GetMaterialInfo(info, deviceModelSavePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

        }

        return null;
    }

    public static List<HH_T_Material> GetMaterialInfo(String jsonData, String deviceModelSavePath) {
        List<HH_T_Material> list = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(jsonData);
            int code = MyJSON.getInt(object,"code");
            if (code == 200){
                JSONArray rows = MyJSON.getJSONArray(object, "rows");
                for (int n = 0; n < rows.length(); n++){
                    JSONObject js = rows.getJSONObject(n);
                    String id = MyJSON.getString(js, "id");
                    String name = MyJSON.getString(js, "name");// 主题名称
                    String themeId = MyJSON.getString(js, "themeId");// 主题ID
                    String themeName = MyJSON.getString(js, "themeName");
                    String size = MyJSON.getString(js, "size");//
                    String fileUrl = MyJSON.getString(js, "fileUrl");
                    String color = MyJSON.getString(js, "color");

                    if (id != null && id.length() > 0 &&
                            themeId != null && themeId.length() > 0 &&
                            fileUrl != null && fileUrl.length() > 0){
                        HH_FileUtil.CreateFolder(deviceModelSavePath + themeId + File.separator);
                        String fileSavePath = deviceModelSavePath + themeId + File.separator + GetPicName(fileUrl);

                        HH_T_Material tl = new  HH_T_Material(id,
                                themeId, themeName,
                                HH_CharUtil.Atol(size),
                                fileUrl,
                                fileSavePath,
                                HH_SystemUtil.GetDeviceColorFormStr(color));
                        list.add(tl);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }

    private static String GetPicName(String fileUrl) {
        if (fileUrl == null || fileUrl.length() <= 0)
            return "";

        String []array = fileUrl.split("/");
        if (array != null && array.length > 0)
            return array[array.length - 1];

        return "";
    }

}
